package com.dragon.framework.config;

import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

/**
 * 验证器配置
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/16 16:52
 */
@Configuration
public class ValidatorConfig {

    /**
     * 校验@RequestBody时，采用快速失败模式
     */
    @Bean
    public Validator validator() {
        try (ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
            .configure()
            // 快速失败
            .failFast(true)
            .buildValidatorFactory()
        ) {
            return validatorFactory.getValidator();
        }
    }

    /**
     * 校验@RequestParam时，采用快速失败模式
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor(Validator validator) {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        // 设置validator
        postProcessor.setValidator(validator);

        return postProcessor;
    }

}
